package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketLog;
import com.cskaoyan.market.service.MarketLogService;
import com.cskaoyan.market.service.MarketLogServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/log/*")
public class AdminLogController extends HttpServlet {
    MarketLogService marketLogService = new MarketLogServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/log/", "");
        if ("list".equals(op)) {
            list(req, resp);
        }

    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        String name = req.getParameter("name");
        Integer limit = null;
        Integer page = null;
        try {
            limit = Integer.parseInt(limitParam);
            page = Integer.parseInt(pageParam);
        } catch (Exception e) {
            //直接返回一个响应结果
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        List<MarketLog> marketLogList = marketLogService.list(page, limit, sort, order, name);
        Object o = ResponseUtil.okList(marketLogList);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
    }
}
